package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"k8s.io/apimachinery/pkg/api/meta"
	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
	"k8s.io/apimachinery/pkg/runtime/serializer/yaml"
	"k8s.io/client-go/discovery"
	"k8s.io/client-go/discovery/cached/memory"
	"k8s.io/client-go/dynamic"
	"k8s.io/client-go/restmapper"
	"k8s.io/client-go/tools/clientcmd"
	"kube-task-scheduling/templates/utils"
	"log"
	"os"
	"path/filepath"
)
var decUnstructured = yaml.NewDecodingSerializer(unstructured.UnstructuredJSONScheme)
func main() {
	//abPath := utils.CurrentPath()
	//
	//fmt.Printf("Current Ab Path is %s \n",abPath)
	abPath := "/Users/wangsj/GolandProjects/person/kube-task-scheduling"

	var kubeconfig string
	if home := homeDir(); home != "" {
		kubeconfig = filepath.Join(home, ".kube", "config")

	}

	config, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
	if err != nil {
		panic(err.Error())
	}
	dc, err := discovery.NewDiscoveryClientForConfig(config)
	if err != nil {
		log.Fatal(err)
	}
	mapper := restmapper.NewDeferredDiscoveryRESTMapper(memory.NewMemCacheClient(dc))

	// 2. Prepare the dynamic client
	dyn, err := dynamic.NewForConfig(config)
	if err != nil {
		log.Fatal(err)
	}

	// 3. Decode YAML manifest into unstructured.Unstructured
	obj := &unstructured.Unstructured{}
	xfiles, _ := utils.GetTempAndValueFile(abPath+"/temp")
	for _, file := range xfiles {
		fmt.Printf("获取的文件为[%s]\n", file)
		byt,_ :=ioutil.ReadFile(file)
		_, gvk, err := decUnstructured.Decode(byt, nil, obj)
		if err != nil {
			log.Fatal(err)
		}
		fmt.Printf("gvk: %#v \n",gvk)
		// 4. Find GVR
		mapping, err := mapper.RESTMapping(gvk.GroupKind(), gvk.Version)
		if err != nil {
			log.Fatal(err)
		}

		// 5. Obtain REST interface for the GVR
		var dr dynamic.ResourceInterface
		if mapping.Scope.Name() == meta.RESTScopeNameNamespace {
			// namespaced resources should specify the namespace
			dr = dyn.Resource(mapping.Resource).Namespace(obj.GetNamespace())
		} else {
			// for cluster-wide resources
			dr = dyn.Resource(mapping.Resource)
		}

		// 6. Marshal object into JSON
		fmt.Printf("obj: %#v \n",obj)
		data, err := json.Marshal(obj)
		if err != nil {
			log.Fatal(err)
		}
		fmt.Printf("dr: %#v \n",dr)
		fmt.Printf("data: %#v \n",string(data))

	}






}

func homeDir() string {
	if h := os.Getenv("HOME"); h != "" {
		return h
	}
	return os.Getenv("USERPROFILE") //windows
}